<template>
  <div>
<!--    购物车-->
    <div v-if="cartlist.length<=0">购物车空空如也</div>
    <table v-else>
      <caption><h3>我的购物车</h3></caption>
      <tr>
        <th></th>
        <th>编号</th>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item,index) in cartlist" :key="item.id">
        <td>
          <input type="checkbox" v-model="item.checked">
        </td>
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.price}}</td>
        <td>
          <button @click="item.num--" :disabled="item.num<=1">-</button>
          {{item.num}}
          <button @click="item.num++">+</button>
        </td>
        <td><a href="#" @click.prevent="del(index)">删除</a></td>
      </tr>
      <tr>
        <td colspan="3" align="right">总价</td>
        <td colspan="3"><small>¥</small> {{ total() }}</td>
      </tr>
    </table>
  </div>
</template>

<script>

export default {
  name: "App",
  data(){
    return{
        cartlist:[
          {id:1, name:'商品1', checked:true, num:1, price:20},
          {id:2, name:'商品2', checked:true, num:1, price:10},
          {id:3, name:'商品3', checked:true, num:1, price:30},
          {id:4, name:'商品4', checked:true, num:1, price:40},
          {id:5, name:'商品5', checked:true, num:1, price:50}
        ]
    }
  },
  methods:{
      del(index){
        this.cartlist.splice(index,1);
      },
    total(){
        //先过滤没选中的 在汇总
       return this.cartlist.filter(n=>n.checked).reduce((prv,cur)=>prv+cur.price*cur.num,0)
    }
  }
}
</script>

<style scoped>
  table {
    width:600px;
    border:1px solid #888888;
    border-collapse: collapse;
  }

  th {
    background: #ccc;
  }

  td, th {
    border:1px solid #888888;
    padding:10px;
  }
</style>